<template>
	<view>

		<u-toast ref="uToast"></u-toast><!-- 弹窗 -->

		<!-- 自定义标题  -->
		<u-navbar :is-back="true" :custom-back="goBack">

			<view style="font-size: 18px;font-weight: bold;margin:0px auto">制程报检单</view>
			<template slot="right">
				<view class="select-all" @click="checkedAll">全选</view>
			</template>
		</u-navbar>

		<!-- 搜索 -->
		<!-- shape="square"方形square、圆形round :clearabled="true"清除内容-->
		<!-- show-action配置是否开启右边按钮控件、action-text配置控件内容
			animation(默认为false)设置为true的话，失去焦点，或者点击控件按钮时，控件自动消失，并且带有动画效果 -->
		<view class="search-box search-box-sticky" style="position: fixed;">
			<u-search placeholder="请输入报检单号搜索" v-model="keyword" height="72" :show-action="false" @change="search"
				bg-color="#f0f2f6" shape="square">
			</u-search>
		</view>

		<!-- 列表 -->
		<view class="inspectSubmission-list-v">
			<view class="list-warp"><!-- :up="upOption" -->
				<!-- <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" top="10"> -->

				<view v-if="loading" class="loading-center-caontainer">
					<!-- 加载动画 -->
					<u-loading mode="flower" size="60"></u-loading>
					<view style="margin-left: 10px;color: gray;">加载中</view>
				</view>
				<template v-else>

					<view v-if="inspectSubs.length > 0">

						<!-- 列表长度大于0-->
						<view class="list">
							<view class="list-box">
								<uni-swipe-action ref="swipeAction"
									style="z-index: 1;"><!-- :right-options="options"  -->
									<!-- key是集合的下标 options是右滑操作 open方法是用于打开一个关闭其他的-->
									<uni-swipe-action-item v-for="(item,key) in inspectSubs" :key="item.id"
										btn-width="300" @open="open" :index="key" :right-options="options"
										@click="debounce($event,item)">
										<view @click="goDetail(item)">
											<view class="item" style="display: flex;" @tap.stop.prevent>
												<u-tag v-if="item.overdue == 2 " text="逾期" shape="square" type="error"
													class="tag-class" />
												<u-tag v-else-if="item.overdue == 1 " text="即将逾期" shape="square"
													type="warning " class="tag-class" />
												<u-tag v-else text="正常" shape="square" type="success"
													class="tag-class" />

												<u-tag v-if="item.status == 0 " text="未确认" shape="square" type="info"
													class="tag-class" />
												<u-tag v-else-if="item.status == 1 " text="执行中" shape="square"
													class="tag-class" />
												<u-tag v-else-if="item.status == 2 " text="已确认" shape="square"
													type="success" class="tag-class" />
												<u-tag v-else="item.status == 3 " text="已关闭" shape="square"
													type="warning" class="tag-class" />
												<u-checkbox class="inspectSub_checkbox" v-model="item.checked"
													:key="item.id"
													:disabled="item.status == 0 ? false : true"></u-checkbox>
												<!-- 不需要@change="checkboxChange" 因为v-model已经绑定了，所以不需要判断多选 -->
											</view>

											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">报检单号</text>
													<text class="listContent">{{item.code ? item.code : ''}}</text>


												</view>
											</view>
											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">报检类型</text>
													<text class="listContent">{{getLableValue(item.type)}}</text>
												</view>
											</view>

											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">工厂信息</text>
													<text class="listContent">
														<template v-if="item.workshopId">
															{{ item.workshopId }}
														</template>
														<template v-if="item.teamId">
															{{ ' '+item.teamId }}
														</template>
														<template v-if="item.workshopSectionId">
															{{ ' '+item.workshopSectionId }}
														</template>
														<template v-if="item.stationId">
															{{ ' '+item.stationId }}
														</template>
													</text>
												</view>
											</view>

											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">物料</text>
													<text
														class="listContent">{{item.materialCode ? item.materialCode : ''}}</text>
												</view>
											</view>

											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">工序</text>
													<text
														class="listContent">{{item.processIdList ? item.processIdList : ''}}</text>
												</view>
											</view>
											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">检验方案</text>
													<text
														class="listContent">{{item.inspectionCase ? item.inspectionCase : ''}}</text>
												</view>
											</view>
											<view class="item">
												<view class="u-line-1 item-cell">
													<text class="listTit u-line-1">检验员</text>
													<text
														class="listContent">{{item.employeeName ? item.employeeName : ''}}</text>
												</view>
											</view>
										</view>

									</uni-swipe-action-item>

									<view style="text-align: center;color:gray;">{{status == 'nomore' ? '没有更多数据' : ''}}
									</view>
								</uni-swipe-action>
							</view>
						</view>

					</view>
				</template>

				<!-- </mescroll-uni> -->
			</view>
		</view>

		<!-- 按钮 -->
		<view class="flowBefore-actions">
			<u-button class="buttom-btn" type="" @click="insert">
				新增
			</u-button>
			<u-button class="buttom-btn" type="primary" @click="confirm">
				确认
			</u-button>
		</view>

		<view>
			<u-modal v-model="showdialog" :title-style="{color: 'red'}" show-cancel-button @confirm="submit">
				<view class="slot-content">
					<u-icon name="error-circle-fill" color="#ffaa00" size="55" style="margin-right: 10px;"></u-icon>
					<rich-text :nodes="content"></rich-text>
				</view>
			</u-modal>
		</view>
		
		<view>
			<u-modal v-model="deletedialog" :title-style="{color: 'red'}" show-cancel-button @confirm="deletesubmit">
				<view class="slot-content">
					<u-icon name="error-circle-fill" color="#ffaa00" size="55" style="margin-right: 10px;"></u-icon>
					<rich-text :nodes="content"></rich-text>
				</view>
			</u-modal>
		</view>
		
		<view>
			<u-modal v-model="closedialog" :title-style="{color: 'red'}" show-cancel-button @confirm="closesubmit">
				<view class="slot-content">
					<u-icon name="error-circle-fill" color="#ffaa00" size="55" style="margin-right: 10px;"></u-icon>
					<rich-text :nodes="content"></rich-text>
				</view>
			</u-modal>
		</view>


	</view>
</template>

<script>
	import {
		ipqcinspection, // 获取数据列表
		DeleteInspectionById, // 删除数据
		ConfirmInspectionByCode, // 确认数据
		CloseInspectionById
	} from '@/api/q1/business/inspection/ipqcinspection.js'
	import {
		getDictionaryDataSelector
	} from '@/api/common.js'
	import resources from '@/libs/resources.js'
	import handleJurisdiction from '@/libs/permission.js'
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js"
	import uLoading from '@/uview-ui/components/u-loading/u-loading.vue'

	export default {
		mixins: [MescrollMixin],
		components: {
			uLoading
		},
		data() {
			return {
				// 上滑加载
				status: 'loadmore', //控制上拉加载的状态
				loading: true, //控制在响应回来前展示loading加载
				pagination: { // 定义分页对象
					pageIndex: 1,
					pageSize: 10,
					total: 1
				},

				// 列表数据
				inspectSubs: [],
				decisionList: [], // 使用决策列表
				disabled: false,
				show: false,
				options: [{
					text: "删除",
					style: {
						backgroundColor: "#dd524d"
					},
				}, {
					text: "关闭",
					style: {
						backgroundColor: "#cecece"
					},
				}],
				isCheckedAll: false, // 全选
				keyword: "", // 搜索内容
				flag: true,
				isShowEmpty: false, // 是否显示空布局
				showdialog: false,
				deletedialog:false,
				content: '',
				deleteid:'',
				closedialog:false,
				closeid:''
			}
		},

		onShow() {
			this.refreshData(); // 刷新
		},

		// 下拉刷新
		onPullDownRefresh() {
			this.inspectSubs = [];
			this.status = 'loadmore';
			this.pagination.pageIndex = 1;
			this.getInspection();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 100);
		},

		// 上滑加载
		onReachBottom() {
			if (this.status !== 'nomore') {
				this.status = 'loading';
				this.pagination.pageIndex++;
				this.getInspection();
			}
		},

		mounted() {

			this.getSelect("465670858640243269") //制程检验类型

		},


		methods: {

			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(key) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.inspectSubs[key].show = true;
				this.inspectSubs.map((val, idx) => {
					if (key != idx) this.inspectSubs[idx].show = false;
				})
			},
			// 新建报检单
			insert() {

				uni.navigateTo({
					url: '/pages/q1/business/processInspection/inspectionedit?pageType=insert'
				})
			},
			// 获取数据
			getInspection() {

				// 条件
				let query = {
					currentPage: this.pagination.pageIndex,
					pageSize: 10,
					code: this.keyword
				}

				ipqcinspection(query).then(res => {
					console.log(res)
					if (res.code === 200) {
						// 获取分页对象
						this.pagination = res.data.pagination;
						// 获取列表数据
						const list = res.data.list.map(o => ({
							...o,
							checked: false
						}));

						if (list.length == 0) {
							this.loading = false;
							this.$refs.uToast.show({
								title: "暂无数据",
								type: 'default'
							})
							return;
						}

						//请求数据数量大于等于总数据量 那就意味已经没有下一页了
						if (list.length === this.pagination.pageSize) {
							var listsize = list.length * this.pagination.pageIndex; //计算加载多少条数据
							if (listsize === this.pagination.total) this.status = 'nomore'; //已经是最后一页
						} else {
							if (list.length < this.pagination.pageSize) this.status = 'nomore'; //已经是最后一页
						}

						// 如果第一页直接赋值，不是第一页将原数组与得到的数组进行合并
						if (this.pagination.pageIndex === 1) this.inspectSubs = list;
						else this.inspectSubs = [...this.inspectSubs, ...list];

					}

					if (this.loading) {
						setTimeout(() => {
							this.loading = false;
						}, 100);
					}

				}).catch((err) => {
					this.$refs.uToast.show({
						title: '异常:' + err,
						type: 'error'
					})
				});
			},

			// 刷新
			refreshData() {
				this.status = 'loadmore';
				this.pagination.pageIndex = 1;
				this.inspectSubs = [];
				this.getInspection();
			},
			// 右滑操作
			//[第一个参数为通过Props传入的index参数，第二个参数为滑动按钮的索引，即options数组的索引， 用于标识第几个按钮被点击。]
			optionClick(event, item) {

				if (this.flag) {
					if (event.index == 0) {
						if (item.status == 0) {
							
							this.deletedialog = true;
							this.content = '此操作将删除该检验批, 是否继续？'
							this.deleteid = item.id;
							
						} else {
							return this.$u.toast("当前任务不能删除!")
						}

					} else if (event.index == 1) {
						if (item.status == 1) {
							
							this.closedialog = true;
							this.content = '此操作将关闭自动生成检验批, 是否继续？'
							this.closeid = item.id;
							
						} else {
							return this.$u.toast("当前任务不能关闭!")
						}
					}
					this.flag = false;
				}
			},
			//删除
			deletesubmit(){
				// 删除
				DeleteInspectionById(this.deleteid).then(res => {
					// true
					if (res.code == 200 && (res.data == null || res.data == "")) {
						this.$refs.uToast.show({
							title: '删除成功',
							type: 'success',
							duration: 500,
							callback: () => {
								this.refreshData();
							},
							bind: this
						})
						return;
					}
				
					// false
					this.$refs.uToast.show({
						title: res.data,
						type: 'error',
					})
				
				}).catch((err) => {
					this.$refs.uToast.show({
						title: '异常:' + err,
						type: 'error',
					})
				});
			},
			closesubmit(){
				// 关闭
				CloseInspectionById(this.closeid).then(res => {
					// true
					if (res.code == 200 && (res.data == null || res.data == "")) {
										
						this.$refs.uToast.show({
							title: '关闭成功',
							type: 'success',
							duration: 500,
							callback: () => {
								this.refreshData();
							},
							bind: this
						})
										
						return;
					}
										
					// false
					this.$refs.uToast.show({
						title: res.data,
						type: 'error',
					})
										
				}).catch((err) => {
					this.$refs.uToast.show({
						title: '异常:' + err,
						type: 'error',
					})
				});
				
			},
			
			// 全选
			checkedAll() {

				// 遍历集合[默认全选,若有一个未选则不是全选]
				this.isCheckedAll = true;
				this.inspectSubs.forEach(item => {

					if (item.checked == false && item.status == 0) {
						this.isCheckedAll = false;
					}

				})
				// 判断是否全选
				if (this.isCheckedAll) {
					// 取消全选
					this.inspectSubs.map(val => {
						val.checked = false;
					})
					this.isCheckedAll = false
				} else {
					// 全选
					this.inspectSubs.map(val => {
						if (val.status == 0) {
							val.checked = true;
						}
					})
					this.isCheckedAll = true
				}
			},

			// 搜索
			search() {

				// 节流,避免输入过快多次请求
				this.searchTimer && clearTimeout(this.searchTimer)
				this.searchTimer = setTimeout(() => {
					this.list = [];
					// 条件
					let query = {
						currentPage: 1,
						pageSize: 10,
						code: this.keyword
					}

					ipqcinspection(query).then(res => {
						const list = res.data.list.map(o => ({
							...o,
							checked: false
						}))
						this.inspectSubs = list;
					})
				}, 300)

			},

			// 防抖函数[1s内flag只允许执行一次]
			debounce(event, item) {
				let timer = null;
				clearTimeout(timer);
				this.flag = true;
				timer = setTimeout(() => {
					this.optionClick(event, item);
				}, 500);
			},

			// 导航栏返回
			goBack() {
				uni.switchTab({
					url: '/pages/index/apply'
				});
			},
			goDetail(item) {

				if (item.status != 0) {
					return this.$u.toast("当前任务不能编辑!")
				} else {
					uni.navigateTo({
						url: '/pages/q1/business/processInspection/inspectionedit?id=' +
							item.id + '&pageType=edit'

					})

				}

			},
			// 加载数据字典下拉框
			getSelect(dictionaryTypeId) {

				getDictionaryDataSelector(dictionaryTypeId).then(res => {

					if (res.code == 200) {
						const list = res.data.list.map(item => {
							return {
								...item,
								id: item.enCode, // 字典项配置的编号
								label: item.fullName // 要显示的数据	
							}
						})
						this.decisionList = list; // 不合格决策				
					}

				}).catch((err) => {
					this.$refs.uToast.show({
						title: '异常:' + err,
						type: 'error'
					})
				});
			},

			getLableValue(value) {
				var lableValue = ''

				this.decisionList.filter(item => {
					if (value == item.enCode) {
						lableValue = item.fullName
					}

				})
				return lableValue
			},

			//确认	
			confirm() {
				var data = [];
				// 获取所有选中的
				this.inspectSubs.forEach(item => {
					if (item.checked) {
						data.push(item.id)
					}
				})
				if (data.length > 0) {
					this.showdialog = true;
					this.content = '您确定要确认这些数据吗, 是否继续？'
				} else {
					return this.$u.toast("请选择一条数据!")
				}
			},
			submit() {
				var data = [];
				// 获取所有选中的
				this.inspectSubs.forEach(item => {
					if (item.checked) {
						data.push(item.id)
					}
				})
				ConfirmInspectionByCode(data).then(res => {
					// true
					if (res.code == 200 && (res.data == null || res.data == "")) {

						this.$refs.uToast.show({
							title: '操作成功',
							type: 'success',
							duration: 100,
							callback: () => {
								this.refreshData();
							},
							bind: this
						})
						return;
					}

				}).catch((err) => {
					alert(err)
				});
			}
		}

	}
</script>

<style lang="scss">
	@import "@/assets/scss/common.scss";

	page {
		background-color: #f0f2f6;
		height: 100%;
		/* #ifdef MP-ALIPAY */
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		/* #endif */
	}

	/* 渲染列表 */
	.item {
		padding: 0 !important;
	}

	/* 列表项标题 */
	.listTit {
		width: 180rpx;
		display: inline-block;
		text-align: left;
		vertical-align: bottom;
		margin-left: 30rpx;
	}

	/* 列表项结果 */
	.listContent {
		margin-left: 20rpx;
		color: #606060;
		height: auto;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* 多选框 */
	.inspectSub_checkbox {

		display: flex;
		align-items: center;
		position: absolute;
		right: 0px;
		top: 10px;


	}

	/* 全选 */
	.select-all {
		padding-right: 40rpx;
	}

	/* 搜索框 */
	.search {
		z-index: 2;
	}

	/* 加载动画 */
	.loading-center-caontainer {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100px;
		margin-top: 80rpx;
	}

	.tag-class {
		margin-top: 10px;
		margin-left: 10px;
	}

	.slot-content {
		display: flex;
		font-size: 30rpx;
		color: $u-content-color;
		padding: 30rpx;

	}
</style>